/** 
 * SocketFactory.java
 * @author Lex
 * 2007-9-2 ����10:50:52
 */
package org.lex.net.proxy;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

/**
 */
public class ProxySocketFactory extends SocketFactory {
	private Proxy proxy = null;

	public ProxySocketFactory() {
		this(Proxy.NO_PROXY);
	}

	public ProxySocketFactory(Proxy proxy) {
		this.proxy = proxy;
	}

	public Proxy getProxy() {
		return proxy;
	}

	public synchronized void setProxy(Proxy proxy) {
		if (null == proxy)
			throw new NullPointerException("Proxy could not be null");
		this.proxy = proxy;
	}

	public Socket createSocket() {
		return new Socket(proxy);
	}

	@Override
	public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
		return this.createSocket(InetAddress.getByName(host), port, null, 10000);
	}

	@Override
	public Socket createSocket(InetAddress host, int port) throws IOException {
		return this.createSocket(host, port, null, 10000);
	}

	@Override
	public Socket createSocket(String host, int port, InetAddress local, int localPort) throws IOException, UnknownHostException {
		return this.createSocket(InetAddress.getByName(host), port, local, localPort);
	}

	@Override
	public Socket createSocket(InetAddress host, int port, InetAddress local, int localPort) throws IOException {
		Socket socket = this.createSocket();
		try {
			if (local != null)
				socket.bind(new InetSocketAddress(local, localPort));
			if (host != null)
				socket.connect(new InetSocketAddress(host, port));
		} catch (IOException e) {
			socket.close();
			throw e;
		}
		return socket;
	}
}
